﻿using LEE.EntityFrameworkCore.Extentions.Entities.Pagination;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LEE.EntityFrameworkCore.Extentions
{
    /// <summary>
    /// EF 分页扩展方法
    /// </summary>
    public static class PaginationExtension
    {
        /// <summary>
        /// 分页查询返回分页数据
        /// </summary>
        /// <typeparam name="T">需返回的数据类型</typeparam>
        /// <param name="query">查询表达式</param>
        /// <param name="request">请求参数</param>
        /// <returns></returns>
        public async static Task<PagingResult<T>> Paging<T>(this IQueryable<T> query, PagingRequest request)
        {
            PagingResult<T> result = new PagingResult<T>
            {
                Page = request.Page,
                Limit = request.Limit
            };
            if (request.EnabledPaging)
            {
                result.TotalCount = await query.CountAsync();
                result.Items = await query.Skip(request.Offset).Take(request.Limit).ToListAsync();
            }
            else
            {
                result.Items = await query.ToListAsync();
                result.TotalCount = result.Items.Count;
            }
            return result;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="query"></param>
        /// <param name="request"></param>
        /// <param name="convertFunc">分页后操作</param>
        /// <returns></returns>
        public static async Task<PagingResult<TResult>> Paging<T, TResult>(this IQueryable<T> query, PagingRequest request, Func<List<T>, IEnumerable<TResult>> convertFunc)
        {
            PagingResult<TResult> result = new PagingResult<TResult>
            {
                Page = request.Page,
                Limit = request.Limit
            };
            List<T> items;
            if (request.EnabledPaging)
            {
                result.TotalCount = await query.CountAsync();
                items = await query.Skip(request.Offset).Take(request.Limit).ToListAsync();
            }
            else
            {
                items = await query.ToListAsync();
                result.TotalCount = items.Count;
            }
            result.Items = convertFunc(items).ToList();
            return result;
        }
    }
}
